﻿using Ces.Entity;
using DevExpress.XtraEditors;
using DevExpress.XtraPrinting.Native.WebClientUIControl;
using MESQWinform;
using MESQWinform.Helper;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MesProjectWinform.BasicData.基础实现.显示页面
{
    public partial class chejian : DevExpress.XtraEditors.XtraForm
    {
        // 添加字段跟踪当前页码和页大小
        private int currentPageIndex = 1;
        private int currentPageSize = 5;
        private string currentShopcode = "";
        private string currentShopname = "";
        // 添加总记录数字段
        private int totalRecords = 0;

        public chejian()
        {
            InitializeComponent();
            
            // 添加刷新按钮
            Button refreshButton = new Button();
            refreshButton.Text = "刷新";
            refreshButton.Size = new Size(75, 23);
            refreshButton.Location = new Point(button1.Location.X + button1.Width + 10, button1.Location.Y);
            refreshButton.Click += refreshButton_Click;
            this.Controls.Add(refreshButton);
        }
        
        ///打开即使用Qry方法
        public async void Qry()
        {
            try
            {
                // 显示等待光标
                this.Cursor = Cursors.WaitCursor;
                
                // 构建查询参数，初始不带任何参数
                string url = "api/WorkShop/GetWorkShop";
                bool hasParam = false;
                
                // 添加workshopcode参数，确保URL编码
                if (!string.IsNullOrEmpty(currentShopcode))
                {
                    string encodedCode = Uri.EscapeDataString(currentShopcode);
                    url += $"?workshopcode={encodedCode}";
                    hasParam = true;
                    Console.WriteLine($"添加编码参数: {encodedCode}");
                }
                
                // 添加workshopname参数，确保URL编码
                if (!string.IsNullOrEmpty(currentShopname))
                {
                    string encodedName = Uri.EscapeDataString(currentShopname);
                    if (hasParam)
                    {
                        url += $"&workshopname={encodedName}";
                    }
                    else
                    {
                        url += $"?workshopname={encodedName}";
                        hasParam = true;
                    }
                    Console.WriteLine($"添加名称参数: {encodedName}");
                }
                
                // 添加分页参数
                if (hasParam)
                {
                    url += $"&pageindex={currentPageIndex}&pagesize={currentPageSize}";
                }
                else
                {
                    url += $"?pageindex={currentPageIndex}&pagesize={currentPageSize}";
                }
                
                Console.WriteLine($"完整查询URL: {url}");
                
                // 调用API
                string json = await APIClientl.CallApiAsync(url);
                Console.WriteLine($"API返回结果: {(json?.Length > 100 ? json.Substring(0, 100) + "..." : json)}");
                
                // 使用动态类型解析JSON - 参考chanxian.cs的实现
                dynamic result = JsonConvert.DeserializeObject<dynamic>(json);
                
                if (result != null)
                {
                    // 计算数据项数量
                    int dataCount = 0;
                    
                    // 使用DataTable存储数据
                    DataTable dt = new DataTable();
                    // 添加所需列
                    dt.Columns.Add("Id", typeof(long));
                    dt.Columns.Add("Workshopcode", typeof(string));
                    dt.Columns.Add("Workshopname", typeof(string));
                    dt.Columns.Add("Workshopdescription", typeof(string));
                    dt.Columns.Add("Workshopattributes", typeof(string));
                    dt.Columns.Add("IsDeleted", typeof(bool));
                    dt.Columns.Add("CreatedBy", typeof(string));
                    dt.Columns.Add("CreatedTime", typeof(DateTime));
                    dt.Columns.Add("UpdatedBy", typeof(string));
                    dt.Columns.Add("UpdatedTime", typeof(DateTime));
                    
                    // 检查Data是否为数组
                    if (result.Data is Newtonsoft.Json.Linq.JArray)
                    {
                        // 如果是数组，遍历每个元素
                        foreach (var item in result.Data)
                        {
                            AddDataRowToTable(dt, item);
                            dataCount++;
                        }
                    }
                    else if (result.Data != null)
                    {
                        // 如果不是数组但不为空，添加单个对象
                        AddDataRowToTable(dt, result.Data);
                        dataCount = 1;
                    }
                    
                    // 显示数据
                    gridControl1.DataSource = dt;
                    Console.WriteLine($"查询到数据条数: {dataCount}");

                    // 获取总记录数
                    totalRecords = result.TotalCount ?? dataCount;
                    
                    // 更新页码状态
                    UpdatePageButtonStatus(dataCount);
                }
                else
                {
                    Console.WriteLine("API返回数据为空或格式错误");
                    // 如果没有数据，清空表格并禁用分页按钮
                    gridControl1.DataSource = null;
                    totalRecords = 0;
                    UpdatePageButtonStatus(0);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"查询异常: {ex.Message}");
                if (ex.InnerException != null)
                {
                    Console.WriteLine($"内部异常: {ex.InnerException.Message}");
                }
                XtraMessageBox.Show($"加载数据出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                
                // 清空表格并禁用分页按钮
                gridControl1.DataSource = null;
                totalRecords = 0;
                UpdatePageButtonStatus(0);
            }
            finally
            {
                // 恢复默认光标
                this.Cursor = Cursors.Default;
            }
        }
        
        /// <summary>
        /// 辅助方法：将动态数据添加到DataTable
        /// </summary>
        /// <param name="dt">要添加数据的DataTable</param>
        /// <param name="item">包含数据的动态对象</param>
        private void AddDataRowToTable(DataTable dt, dynamic item)
        {
            try
            {
                DataRow row = dt.NewRow();
                
                // 使用TryGetValue方式安全地获取属性值
                row["Id"] = GetDynamicValue(item, "Id", 0L);
                row["Workshopcode"] = GetDynamicValue(item, "Workshopcode", string.Empty);
                row["Workshopname"] = GetDynamicValue(item, "Workshopname", string.Empty);
                row["Workshopdescription"] = GetDynamicValue(item, "Workshopdescription", string.Empty);
                row["Workshopattributes"] = GetDynamicValue(item, "Workshopattributes", DBNull.Value);
                row["IsDeleted"] = GetDynamicValue(item, "IsDeleted", false);
                row["CreatedBy"] = GetDynamicValue(item, "CreatedBy", DBNull.Value);
                row["CreatedTime"] = GetDynamicValue(item, "CreatedTime", DateTime.Now);
                row["UpdatedBy"] = GetDynamicValue(item, "UpdatedBy", DBNull.Value);
                row["UpdatedTime"] = GetDynamicValue(item, "UpdatedTime", DateTime.Now);
                
                dt.Rows.Add(row);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"添加数据行失败: {ex.Message}");
                // 错误处理但继续执行，不抛出异常
            }
        }
        
        /// <summary>
        /// 辅助方法：安全获取动态对象的属性值
        /// </summary>
        /// <typeparam name="T">属性值类型</typeparam>
        /// <param name="obj">动态对象</param>
        /// <param name="propertyName">属性名称</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>属性值或默认值</returns>
        private T GetDynamicValue<T>(dynamic obj, string propertyName, T defaultValue)
        {
            try
            {
                // 检查是否为JObject类型
                if (obj is Newtonsoft.Json.Linq.JObject jObject)
                {
                    if (jObject.ContainsKey(propertyName))
                    {
                        return jObject[propertyName].ToObject<T>();
                    }
                    
                    // 检查小写属性名称
                    string lcPropertyName = propertyName.ToLower();
                    foreach (var prop in jObject.Properties())
                    {
                        if (prop.Name.ToLower() == lcPropertyName)
                        {
                            return prop.Value.ToObject<T>();
                        }
                    }
                    
                    return defaultValue;
                }
                
                // 尝试通过反射获取属性值
                var value = obj.GetType().GetProperty(propertyName)?.GetValue(obj, null);
                if (value == null)
                    return defaultValue;
                
                return (T)Convert.ChangeType(value, typeof(T));
            }
            catch
            {
                return defaultValue;
            }
        }

        // 更新分页按钮状态
        private void UpdatePageButtonStatus(int currentDataCount)
        {
            // 上一页按钮：当前页大于1时启用
            button4.Enabled = currentPageIndex > 1;
            
            // 下一页按钮：根据总记录数和当前页码判断是否有下一页
            int totalPages = (int)Math.Ceiling((double)totalRecords / currentPageSize);
            button3.Enabled = currentPageIndex < totalPages;
            
            // 不再在标题中显示分页信息
            // this.Text = $"车间管理 - 第{currentPageIndex}页/共{totalPages}页 (每页{currentPageSize}条，共{totalRecords}条记录)";
        }
        /// <summary>
        /// 双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridControl1_Click(object sender, EventArgs e)
        {
          
        }

        private void chejian_Load(object sender, EventArgs e)
        {
            // 页面加载时显示所有数据，使用默认参数
            Qry();
        

        }
      
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取查询参数
                currentShopcode = textEdit1.Text.Trim(); // 车间编号
                currentShopname = textEdit2.Text.Trim(); // 车间名称
                
                // 输出调试信息
                Console.WriteLine($"执行查询: 编码={currentShopcode}, 名称={currentShopname}");
                
                // 重置页码为1（新查询从第一页开始）
                currentPageIndex = 1;
                
                // 调用Qry方法进行查询
                Qry();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"查询出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            jianCreate jianCreate = new jianCreate();
            // 订阅DataAdded事件，当添加数据成功后刷新页面
            jianCreate.DataAdded += () => 
            {
                // 在UI线程上调用Qry方法刷新数据
                if (this.InvokeRequired)
                {
                    this.Invoke(new Action(() => Qry()));
                }
                else
                {
                    Qry();
                }
            };
            jianCreate.ShowDialog();
        }
        
        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            // 确保页码大于1
            if (currentPageIndex > 1)
            {
                currentPageIndex--;
                Qry();
            }
        }
        
        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            // 计算总页数
            int totalPages = (int)Math.Ceiling((double)totalRecords / currentPageSize);
            
            // 确保不超过总页数
            if (currentPageIndex < totalPages)
            {
                currentPageIndex++;
                Qry();
            }
        }
        
        private void repositoryItemButtonEdit1_Click(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void repositoryItemButtonEdit2_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                // 获取当前选中行的数据
                var view = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
                if (view != null && view.GetSelectedRows().Length > 0)
                {
                    int rowHandle = view.GetSelectedRows()[0];
                    long id = Convert.ToInt64(view.GetRowCellValue(rowHandle, "Id"));
                    
                    // 调用删除API，使用PUT方法
                    string url = $"api/WorkShop/DeleteWorkShop?id={id}";
                    await APIClientl.CallApiAsync(url, "PUT");
                    
                    // 刷新数据，使用GET方法
                    Qry();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"删除失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 不在使用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void repositoryItemCalcEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
         
        }
        /// <summary>
        /// 使用的修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void repositoryItemButtonEdit3_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                // 获取当前选中行的数据
                var view = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
                if (view != null && view.GetSelectedRows().Length > 0)
                {
                    int rowHandle = view.GetSelectedRows()[0];
                    
                    // 获取完整的车间信息
                    long id = Convert.ToInt64(view.GetRowCellValue(rowHandle, "Id"));
                    string code = Convert.ToString(view.GetRowCellValue(rowHandle, "Workshopcode"));
                    string name = Convert.ToString(view.GetRowCellValue(rowHandle, "Workshopname"));
                    string description = Convert.ToString(view.GetRowCellValue(rowHandle, "Workshopdescription"));
                    
                    Console.WriteLine($"打开修改窗体，ID: {id}, 编码: {code}, 名称: {name}");
                    
                    // 创建jianup窗体并传递完整车间信息
                    jianup jianup = new jianup(id, code, name, description);
                    
                    // 订阅数据更新事件，当修改成功后刷新页面
                    jianup.DataUpdated += () => 
                    {
                        Console.WriteLine($"收到修改成功事件，正在刷新数据...");
                        // 在UI线程上调用Qry方法刷新数据
                        if (this.InvokeRequired)
                        {
                            this.Invoke(new Action(() => {
                                Console.WriteLine("在UI线程上执行刷新");
                                Qry();
                            }));
                        }
                        else
                        {
                            Console.WriteLine("直接执行刷新");
                            Qry();
                        }
                    };
                    
                    // 显示修改窗体
                    jianup.ShowDialog();
                    
                    // 窗体关闭后，再次刷新一下数据，确保显示最新的数据
                    Console.WriteLine("修改窗体已关闭，再次刷新数据...");
                    RefreshData();
                }
                else
                {
                    XtraMessageBox.Show("请先选择要修改的行", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"修改操作异常: {ex.Message}");
                XtraMessageBox.Show($"获取数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 手动刷新数据
        /// </summary>
        public void RefreshData()
        {
            try
            {
                Console.WriteLine("手动刷新数据");
                // 保持当前查询条件，刷新数据
                Qry();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"刷新数据出错: {ex.Message}");
                XtraMessageBox.Show($"刷新数据出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 刷新按钮点击事件
        /// </summary>
        private void refreshButton_Click(object sender, EventArgs e)
        {
            RefreshData();
        }
    }
}